package com.example.teacherservice.repository;

import com.example.teacherservice.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

// CommentRepository.java
public interface CommentRepository extends JpaRepository<Comment, Long> {
    List<Comment> findByQuestionIdAndDeleted(Long questionId, Integer deleted);
    List<Comment> findByStudentIdAndDeleted(Long studentId, Integer deleted);
    List<Comment> findByTeacherIdAndDeleted(Long teacherId, Integer deleted);

    // 统一查询用户(学生/教师)的评论
    @Query("SELECT c FROM Comment c WHERE " +
            "(c.studentId = :userId OR c.teacherId = :userId) AND c.deleted = 0")
    List<Comment> findByUserId(@Param("userId") Long userId);

    // 统一检查评论归属
    @Query("SELECT CASE WHEN COUNT(c) > 0 THEN true ELSE false END " +
            "FROM Comment c WHERE c.id = :commentId AND " +
            "(c.studentId = :userId OR c.teacherId = :userId) AND c.deleted = 0")
    boolean isCommentBelongsToUser(@Param("commentId") Long commentId,
                                   @Param("userId") Long userId);

    // 添加计数方法
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.questionId = :questionId AND c.deleted = 0")
    long countByQuestionId(@Param("questionId") Long questionId);

    @Modifying
    @Query("DELETE FROM Comment c WHERE c.questionId = :questionId")
    void deleteByQuestionId(@Param("questionId") Long questionId);

    @Modifying
    @Query("DELETE FROM Comment c WHERE c.replyId = :replyId")
    void deleteByReplyId(@Param("replyId") Long replyId);

    @Modifying
    @Query("DELETE FROM Comment c WHERE c.id = :commentId AND (c.studentId = :userId OR c.teacherId = :userId)")
    int deleteUserComment(@Param("commentId") Long commentId, @Param("userId") Long userId);

    @Modifying
    @Query("DELETE FROM Comment c WHERE c.replyId = :commentId")
    void deleteReplies(@Param("commentId") Long commentId);

}
